package com.ilide.msgManage.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.ilide.msgManage.exception.BusinessException;
import com.ilide.msgManage.config.AliSmsConfig;
import com.ilide.msgManage.model.dto.AliSmsSendDTO;
import com.ilide.msgManage.model.po.SmsSendLog;
import com.ilide.msgManage.utils.GsonUtil;
import com.ilide.msgManage.utils.WebResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 阿里云短信发送服务
 *
 * @author pg
 * @date 2020年3月20日 10:15:03
 */
@Slf4j
@Service
public class AliSmsService {

    @Autowired
    private AliSmsConfig aliConfig;
    /**
     * 发送短信
     *
     * @param phoneNumber 接收短信的手机号
     * @param templateCode 发送短信使用的模版
     * @param sendData 发送的内容，根据模版变化
     * @return
     * @throws BusinessException
     */
    public WebResult sendSms(String phoneNumber, String templateCode, Map sendData){
        try {
            //初始化短信发送client
            DefaultProfile profile = DefaultProfile.getProfile(aliConfig.getRegionId(), aliConfig.getAccessKeyId(), aliConfig.getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);

            //初始化发送验证码参数
            SendSmsRequest request = new SendSmsRequest();
            request.putQueryParameter("PhoneNumbers", phoneNumber);
            request.putQueryParameter("SignName", aliConfig.getSignName());
            request.putQueryParameter("TemplateCode", templateCode);
            request.putQueryParameter("TemplateParam", GsonUtil.toJson(sendData));
            //调用阿里云短信发送接口
            SendSmsResponse response = client.getAcsResponse(request);
            if (response.getCode().equals("OK")){
                return WebResult.ok(sendData);
            } else {
                return WebResult.wrong(response.getMessage());
            }
        } catch (Exception e) {
            log.error("发送短信失败！", e);
            return WebResult.wrong("发送短信失败！" + e.getMessage());
        }
    }

}
